package com.math.aistudykbr.handler;

import com.math.aistudykbr.constant.MessageConstants;
import com.math.aistudykbr.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
 * 在 @ExceptionHandler 方法中，返回 ResponseEntity（包含状态码和响应体），
 * Spring 会直接将其转换为 HTTP 响应并发送给客户端，后续处理链终止。
 */
@RestControllerAdvice
@RequiredArgsConstructor
@Slf4j
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e, HttpServletRequest request) {
        // 1. 记录异常
        logger.error("Exception occurred on {}: ", request.getRequestURI(), e);

        // 2. 如果是SSE请求，返回SseEmitter错误
        if (request.getRequestURI().startsWith("/api/sse/")) {
            SseEmitter emitter = new SseEmitter();
            try {
                emitter.send(SseEmitter.event()
                        .name("error")
                        .data(e.getMessage())
                        .id("error-" + System.currentTimeMillis())
                );
                emitter.completeWithError(e);
            } catch (IOException ex) {
                log.error("Failed to send SSE error", ex);
            }
            return emitter;
        }

        // 3. 普通请求返回JSON
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new Result(500, MessageConstants.ServerError + ": " + e.getMessage(), null));
    }
}